package org.jeecg.modules.alarm.vo;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zhouwr.common.enums.MessageEventType;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.modules.alarm.entity.AlarmConfigTrigger;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @program: forallcn-iotps
 * @description:
 * @author: zhouwr
 * @create: 2021-01-15 11:59
 * @version：1.0
 **/
@Data
@NoArgsConstructor
public class AlarmConfigTriggerVo {
    List<TriggerFilterVo> filters;
    private String id;
    private String name;
    private String modelDataId;
    private MessageEventType source;

    public AlarmConfigTriggerVo(AlarmConfigTrigger trigger) {
        this.id = trigger.getId();
        this.name = trigger.getName();
        this.source = trigger.getSource();
        this.modelDataId = trigger.getDataId();
        this.filters = JSONArray.parseArray(trigger.getFilterRule(), TriggerFilterVo.class);
    }

    /**
     * 获取过滤器表达式
     *
     * @return
     */
    public String getFilterExpre() {
        return this.filters.stream()
                .map(
                        triggerFilterVo -> triggerFilterVo.getFilterKey()
                                + triggerFilterVo.getFilterRule()
                                + triggerFilterVo.getFilterValue())
                .collect(Collectors.joining("&"));
    }

    public String getFilterExpre(Set<String> dataCode) {
        return this.filters.stream()
                .filter(triggerFilterVo -> dataCode.contains(triggerFilterVo.getFilterKey()))
                .map(
                        triggerFilterVo -> triggerFilterVo.getFilterKey()
                                + triggerFilterVo.getFilterRule()
                                + triggerFilterVo.getFilterValue())
                .filter(StringUtils::isNotBlank)
                .collect(Collectors.joining("&&"));
    }
}

@Data
@NoArgsConstructor
@AllArgsConstructor
class TriggerFilterVo {
    private String filterKey;
    private String filterRule;
    private Object filterValue;

    public JSONObject toJSONObject() {
        JSONObject json = new JSONObject();
        json.put("filterKey", filterKey);
        json.put("filterRule", filterRule);
        json.put("filterValue", filterValue);
        return json;
    }
}
